import { useMemo, useState } from 'react';
import { ScrollView } from '@tarojs/components';
import { useRequest } from 'ahooks';
import Taro from '@tarojs/taro';
import styles from './index.module.less';
import { useCityStore } from '@/common/hox/cityStore';
import SearchBar from '@/components/SearchBar';
import { getMovieCityList } from '@/service';
import { withPageContainer } from '@/components';
const ChooseCityPage = () => {
    const { setMovieLocation, movieLocation, refresh } = useCityStore();

    const openLocation = () => {
        refresh();
        // awaitPosition()
    };
    const [searchValue, setSearchValue] = useState<string>();

    // 获取城市列表
    const getMovieCityListApi = useRequest(getMovieCityList, {
        onBefore: () => Taro.showLoading({
            title:'加载中'
        }),
        onFinally: () => Taro.hideLoading(),
    });

    // 展示的城市列表
    const showMovieCityList = useMemo(() => {
        const data = getMovieCityListApi.data?.list || [];
        const res = data.reduce<Record<string, City.List[]>>((pre, cur) => {
            const { initial } = cur;
            if (!pre[initial]) pre[initial] = [];
            pre[initial].push(cur);
            return pre;
        }, {});
        const cityList = Object.entries(res).sort();
        // 热门城市
        const hotCityNames = [
            '北京市',
            '上海市',
            '广州市',
            '深圳市',
            '杭州市',
            '成都市',
            '武汉市',
            '南京市',
            '北京',
            '上海',
            '广州',
            '深圳',
            '杭州',
            '成都',
            '武汉',
            '南京',
        ];
        const hotCityList =
            (getMovieCityListApi.data?.list || [])?.filter((item) =>
                hotCityNames.includes(item.city)
            ) || [];
        cityList.unshift(['热门城市', hotCityList]);
        return cityList;
    }, [getMovieCityListApi.data]);

    // 筛选搜索城市列表
    const searchedMovieCityList = useMemo(() => {
        if (searchValue) {
            const data = getMovieCityListApi.data?.list || [];
            return data.filter(
                (item) => item.city.includes(searchValue) || item.pinyin.includes(searchValue)
            );
        }
    }, [getMovieCityListApi.data, searchValue]);

    // 点击城市item回调
    const onCitySelect = (cityInfo: City.List) => {
        // 缓存城市信息至store
        setMovieLocation(cityInfo);
        const pages = Taro.getCurrentPages();
        if (pages.length > 1) {
            Taro.navigateBack();
        } else {
            Taro.reLaunch({ url: '/pages/index/index' });
        }
    };

    const [scrollIntoView, setScrollIntoView] = useState<string>();

    return (
        <div className={styles.page}>
            <SearchBar
                className={styles.searchBar}
                value={searchValue}
                onChange={setSearchValue}
                placeholder="请输入城市"
            />
            <div className={styles.content}>
                {searchedMovieCityList ? (
                    <ScrollView style={{ height: '100%' }} scrollY>
                        {searchedMovieCityList.map((item) => {
                            const { city, cityId } = item;
                            return (
                                <div
                                    key={cityId}
                                    className={styles.searchCityItem}
                                    onClick={() => onCitySelect(item)}
                                >
                                    {city}
                                </div>
                            );
                        })}
                    </ScrollView>
                ) : (
                    <>
                        <div className={styles.guid}>
                            {showMovieCityList.map((item) => {
                                const [initial] = item;
                                return (
                                    <div
                                        className={styles.guidItem}
                                        key={initial}
                                        onClick={() => setScrollIntoView(initial)}
                                    >
                                        {initial.split('')[0]}
                                    </div>
                                );
                            })}
                        </div>
                        <ScrollView
                            style={{ height: '100%' }}
                            scrollY
                            scrollIntoViewAlignment="start"
                            scrollIntoView={scrollIntoView}
                        >
                            <div>
                                <div className={styles.box}>
                                    <div className={styles.subtitle}>
                                        当前定位
                                        <span className={styles.subtitleTxt}>
                                            {movieLocation?.city ? movieLocation?.city : '未开启'}
                                        </span>
                                    </div>
                                    <div className={styles.btnPicBox}>
                                        <div className={styles.btnPic}></div>
                                    </div>
                                    <div className={styles.btnItem} onClick={openLocation}>
                                        重新定位
                                    </div>
                                </div>
                            </div>
                            {showMovieCityList.map((item) => {
                                const [initial, cityList] = item;
                                return (
                                    <div key={initial} id={initial}>
                                        <div className={styles.title}>{initial}</div>
                                        <div className={styles.box}>
                                            {cityList.map((item) => {
                                                const { city, cityId } = item;
                                                return (
                                                    <div
                                                        key={initial + cityId}
                                                        className={styles.cityItem}
                                                        onClick={() => onCitySelect(item)}
                                                    >
                                                        {city}
                                                    </div>
                                                );
                                            })}
                                        </div>
                                    </div>
                                );
                            })}
                        </ScrollView>
                    </>
                )}
            </div>
        </div>
    );
};

export default withPageContainer(() => <ChooseCityPage />);
